package com.bigkoo.pickerview.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;

import com.bigkoo.pickerview.LinkageOptionsPickerView.OnOptionsSelectListener2;
import com.bigkoo.pickerview.R;
import com.bigkoo.pickerview.listener.OnDismissListener;
import com.bigkoo.pickerview.utils.PickerViewAnimateUtil;

/**
 * 精仿iOSPickerViewController控件
 *
 * @author Created by Sai on 15/11/22.
 */
public abstract class BasePickerView {
    
    protected final FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER
    );
    
    private final Context mContext;
    // 如果已非Dialog模式展示，此为界面展示需要添加到的父布局
    private ViewGroup mDecorView;
    // 弹窗的根布局
    private ViewGroup mDialogRootView;
    // 显示界面实际内容布局
    protected ViewGroup mContentContainer;
    
    protected int pickerview_timebtn_nor = 0xFF057dff;
    protected int pickerview_bg_topbar = 0xFFf5f5f5;
    protected int pickerview_topbar_title = 0xFF000000;
    protected int bgColor_default = 0xFFFFFFFF;
    
    private OnDismissListener mOnDismissListener;
    private boolean mDismissing;
    
    private Animation mOutAnim;
    private Animation mInAnim;
    private boolean isShowing;
    private int mGravity = Gravity.CENTER;
    
    private Dialog mDialog;
    // 是否能取消
    private boolean mCancelable;
    private boolean isAnim = true;
    
    public BasePickerView(Context context) {
        this.mContext = context;
    }
    
    @SuppressLint("InflateParams")
    protected void initViews(int backgroundId) {
        LayoutInflater layoutInflater = LayoutInflater.from(mContext);
        if (isDialog()) {
            // 如果是对话框模式
            mDialogRootView = (ViewGroup) layoutInflater.inflate(R.layout.layout_basepickerview, null, false);
            // 设置界面的背景为透明
            mDialogRootView.setBackgroundColor(Color.TRANSPARENT);
            // 这个是真正要加载时间选取器的父布局
            mContentContainer = (ViewGroup) mDialogRootView.findViewById(R.id.content_container);
            mContentContainer.setLayoutParams(this.params);
            // 创建对话框
            createDialog();
        } else {
            // 只是要显示在屏幕的下方
            // decorView是activity的根View
            if (mDecorView == null) {
                mDecorView = (ViewGroup) ((Activity) mContext).getWindow().getDecorView().findViewById(android.R.id.content);
            }
            // 将控件添加到decorView中
            mDialogRootView = (ViewGroup) layoutInflater.inflate(R.layout.layout_basepickerview, mDecorView, false);
            mDialogRootView.setLayoutParams(new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
            ));
            if (backgroundId != 0) {
                mDialogRootView.setBackgroundColor(backgroundId);
            }
            mContentContainer = (ViewGroup) mDialogRootView.findViewById(R.id.content_container);
            mContentContainer.setLayoutParams(params);
            setOutSideCancelable(mCancelable);
            setKeyBackCancelable();
        }
    }
    
    protected void init() {
        mInAnim = getInAnimation();
        mOutAnim = getOutAnimation();
    }
    
    protected void initEvents() {
    
    }
    
    public void setDecorView(ViewGroup view) {
        this.mDecorView = view;
    }
    
    public Context getContext() {
        return mContext;
    }
    
    public void show(boolean isAnim) {
        this.isAnim = isAnim;
        show();
    }
    
    /**
     * 添加View到根视图
     */
    public void show() {
        if (isDialog()) {
            showDialog();
        } else {
            if (isAttachToParent()) {
                return;
            }
            
            isShowing = true;
            onAttached(mDialogRootView);
            mDialogRootView.requestFocus();
        }
    }
    
    /**
     * show的时候调用
     *
     * @param view 这个View
     */
    private void onAttached(View view) {
        mDecorView.addView(view);
        if (isAnim) {
            mContentContainer.startAnimation(mInAnim);
        }
    }
    
    /**
     * 检测非Dialog时，该View是不是已经添加到根视图
     *
     * @return 如果视图已经存在该View返回true
     */
    private boolean isAttachToParent() {
        if (isDialog()) {
            return false;
        } else {
            return mDialogRootView.getParent() != null || isShowing;
        }
    }
    
    public boolean isShowing() {
        if (isDialog()) {
            return mDialog.isShowing();
        } else {
            return mDialogRootView.getParent() != null || isShowing;
        }
    }
    
    public void dismiss() {
        if (isDialog()) {
            dismissDialog();
        } else {
            if (mDismissing) {
                return;
            }
            
            if (isAnim) {
                //消失动画
                mOutAnim.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                    
                    }
                    
                    @Override
                    public void onAnimationEnd(Animation animation) {
                        dismissImmediately();
                    }
                    
                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    
                    }
                });
                mContentContainer.startAnimation(mOutAnim);
            } else {
                dismissImmediately();
            }
            mDismissing = true;
        }
    }
    
    private void dismissImmediately() {
        mDecorView.post(() -> {
            // 从根视图移除
            mDecorView.removeView(mDialogRootView);
            isShowing = false;
            mDismissing = false;
            if (mOnDismissListener != null) {
                mOnDismissListener.onDismiss(BasePickerView.this);
            }
        });
    }
    
    public Animation getInAnimation() {
        int res = PickerViewAnimateUtil.getAnimationResource(this.mGravity, true);
        return AnimationUtils.loadAnimation(mContext, res);
    }
    
    public Animation getOutAnimation() {
        int res = PickerViewAnimateUtil.getAnimationResource(this.mGravity, false);
        return AnimationUtils.loadAnimation(mContext, res);
    }
    
    public void setOnDismissListener(OnDismissListener onDismissListener) {
        this.mOnDismissListener = onDismissListener;
    }
    
    /**
     * 设置键盘按键监听
     */
    private void setKeyBackCancelable() {
        if (isDialog() || mDialogRootView == null) {
            return;
        }
        
        mDialogRootView.setFocusable(true);
        mDialogRootView.setFocusableInTouchMode(true);
        mDialogRootView.setOnKeyListener((v, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == MotionEvent.ACTION_DOWN
                && isAttachToParent()) {
                dismiss();
                return true;
            }
            return false;
        });
    }
    
    /**
     * 设置点击外部是否可以关闭弹窗
     */
    @SuppressLint("ClickableViewAccessibility")
    protected void setOutSideCancelable(boolean isCancelable) {
        this.mCancelable = isCancelable;
        if (mDialog != null) {
            mDialog.setCanceledOnTouchOutside(isCancelable);
            return;
        }
        
        if (mDialogRootView != null) {
            mDialogRootView.setOnTouchListener((v, event) -> {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    float x = event.getX();
                    float y = event.getY();
                    float x1 = mContentContainer.getX();
                    float y1 = mContentContainer.getY();
                    if ((x < x1 - 10) || (x > x1 + mContentContainer.getWidth() + 10)
                        || ((y < y1 - 10) || (y > y1 + mContentContainer.getHeight() + 10))) {
                        dismiss();
                    }
                }
                return true;
            });
        }
    }
    
    /**
     * 获取弹窗内容布局
     */
    public View getContentView() {
        return mContentContainer;
    }
    
    public View findViewById(int id) {
        return mContentContainer.findViewById(id);
    }
    
    private void createDialog() {
        if (mDialogRootView != null) {
            mDialog = new Dialog(mContext, R.style.custom_dialog2);
            mDialog.setCancelable(false);
            mDialog.setContentView(mDialogRootView);
            mDialog.setCanceledOnTouchOutside(mCancelable);
            
            Window window = mDialog.getWindow();
            View decorView = window.getDecorView();
            decorView.setPadding(0, 0, 0, 0);
            WindowManager.LayoutParams layoutParams = window.getAttributes();
            layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
            window.setAttributes(layoutParams);
            window.setWindowAnimations(R.style.pickerview_dialogAnim);
            mDialog.setOnDismissListener(dialog -> {
                if (mOnDismissListener != null) {
                    mOnDismissListener.onDismiss(BasePickerView.this);
                }
            });
        }
    }
    
    private void showDialog() {
        if (mDialog != null) {
            mDialog.show();
        }
    }
    
    private void dismissDialog() {
        if (mDialog != null) {
            mDialog.dismiss();
        }
    }
    
    /**
     * 设置控件显示位置，默认显示在屏幕中间
     *
     * @param gravity 只支持{@link Gravity#CENTER}和{@link Gravity#BOTTOM},如果设置其它值，则使用默认值
     */
    public void setGravity(int gravity) {
        if (gravity == Gravity.CENTER || gravity == Gravity.BOTTOM) {
            params.gravity = gravity;
            this.mGravity = gravity;
        } else {
            params.gravity = Gravity.CENTER;
            this.mGravity = Gravity.CENTER;
        }
    }
    
    /**
     * 是否已弹窗方式实现
     */
    public boolean isDialog() {
        return true;
    }
    
    /**
     * 回调用户选中的数据
     */
    public abstract void returnData();
    
    /**
     * 回调用户选中的数据
     *
     * @param view 用于{@link OnOptionsSelectListener2}回调
     */
    public abstract void returnData(View view);
}
